<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" placeholder="请输入姓名" v-model.trim="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" placeholder="请输入年龄" v-model.number="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div v-if="list.length !=0">
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(val ,index) in list" :key="index">
          <td>{{index + 1}}</td>
          <td>{{val.name}}</td>
          <td>{{val.age}}</td>
          <td>{{val.sex}}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="bjbtn(val,index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
import Vue from "vue";
export default {
  data() {
    return {
      list: JSON.parse(localStorage.getItem("a")) || [
        {
          name: "小王",
          age: "18",
          sex: "男",
        },
      ],
      name: "",
      age: "",
      sex: "",
      aindex: -1,
    };
  },
  methods: {
    // 删除功能
    del(idx) {
      this.list.splice(idx, 1);
    },
    // 添加或者修改
    add() {
      let obj = {
        name: this.name,
        age: this.age,
        sex: this.sex,
      };

      this.aindex == -1
        ? this.list.push(obj)
        : Vue.set(this.list, this.aindex, obj);
      // 点击完成后初始化显示框
      this.aindex = -1;
      this.name = "";
      this.age = 0;
      this.sex = "";
    },
    // 编辑回显
    bjbtn(val, idx) {
      console.log(idx);
      this.name = val.name;
      this.age = val.age;
      this.sex = val.sex;
      this.aindex = idx;
    },
  },
  watch: {
    list: {
      handler(newVal) {
        localStorage.setItem("a", JSON.stringify(newVal));
      },
      deep: true,
    },
  },
};
</script>
